package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {


    @Resource
    DishMapper dishMapper;

    @Resource
    DishFlavorMapper dishFlavorMapper;

    @Transactional
    @Override
    public void save(DishDTO dishDTO) {


        String name = dishDTO.getName();
        Long categoryId = dishDTO.getCategoryId();
        BigDecimal price = dishDTO.getPrice();
        String image = dishDTO.getImage();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(categoryId == null || !StrUtil.isNotBlank(image) || !StrUtil.isNotBlank(name) || price == null) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }
        Long currentId = BaseContext.getCurrentId();
        if(currentId != 1) {
            throw new BaseException(MessageConstant.NO_AUTH);
        }

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.save(dish);
        // 得到当前插入数据库里面的最新dash_id
        Long id = dish.getId();
        // System.out.println("-------------------------" + id);
        // 将最新的dash_id设置进dash_flavor里面
        List<DishFlavor> collect = flavors.stream().map(dishFlavor -> {
            dishFlavor.setDishId(id);
            return dishFlavor;
        }).collect(Collectors.toList());
        // System.out.println("-------------------------" + collect);
        if(flavors != null && flavors.size() > 0) {
            dishFlavorMapper.saveBatch(collect);
        }

    }

    @Override
    public DishVO getById(Long id) {
        DishVO dishVO = new DishVO();

        // 获得dish信息
        Dish dish = dishMapper.selectById(id);
        if(dish == null) {
            throw new BaseException(MessageConstant.NO_EXIST);
        }
        BeanUtils.copyProperties(dish, dishVO);
        // 得到关联风味的id
        Long dishId = dish.getId();
        // 根据关联分类id查询风味信息
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(dishId);

        dishVO.setFlavors(flavors);
        return dishVO;
    }

    @Override
    public List<Dish> getCategoryById(Long categoryId) {
        List<Dish> categoryById = dishMapper.getCategoryById(categoryId);
        return categoryById;
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();

        PageHelper.startPage(page, pageSize);
        Page<Dish> dishList = dishMapper.pageQuery(name, categoryId, status);



        PageResult pageResult = new PageResult();
        pageResult.setTotal(dishList.getTotal());
        pageResult.setRecords(dishList.getResult());


        return pageResult;
    }

    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        Long id = dishDTO.getId();
        String name = dishDTO.getName();
        Long categoryId = dishDTO.getCategoryId();
        BigDecimal price = dishDTO.getPrice();
        String image = dishDTO.getImage();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(categoryId == null || id == null || price == null
                || !StrUtil.isNotBlank(image) || !StrUtil.isNotBlank(name)) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);


        if(flavors != null && flavors.size() > 0) {
            dishFlavorMapper.delectByDishId(id);
            List<DishFlavor> collect = flavors.stream().map(dishFlavor -> {
                dishFlavor.setDishId(id);
                return dishFlavor;
            }).collect(Collectors.toList());
            dishFlavorMapper.saveBatch(collect);
        }
    }

    @Transactional
    @Override
    public void deleteBatchByIds(List<Long> ids) {
        if(ids == null || ids.size() == 0) {
            return;
        }
        Long currentId = BaseContext.getCurrentId();
        if(currentId != 1) {
            throw new BaseException(MessageConstant.NO_AUTH);
        }
        for (Long id : ids) {
            // 删除dishid为当前id的值的dishflavor
            dishFlavorMapper.delectByDishId(id);
            // 按照id删除dish
            dishMapper.deleteById(id);
        }
    }

    @Override
    public void changeStatus(Integer status, Long id) {
        if(status == null || id == null) {
            throw new BaseException(MessageConstant.PARAM_ERROR);
        }
        Long currentId = BaseContext.getCurrentId();
        if(currentId != 1) {
            throw new BaseException(MessageConstant.NO_AUTH);
        }
        dishMapper.changeStatus(status, id);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getCategoryById(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    @Override
    public DishOverViewVO overviewDishs() {
        Integer sold = dishMapper.getByStatus(StatusConstant.ENABLE);
        Integer discontinued = dishMapper.getByStatus(StatusConstant.DISABLE);
        return DishOverViewVO.builder()
                .discontinued(discontinued)
                .sold(sold)
                .build();
    }
}
